package com.example.first.thread;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author LSQ
 * @Description 创建六个任务，把六个任务都放到线程池里面；每个任务对共享资源加锁
 * @date 2021/11/5 21:47
 * @Version 1.0
 */

public class LearnReentrantLock2 {

    private static final int CORE_POOL_SIZE = 3;
    private static final int MAX_POOL_SIZE = 50;
    private static final int QUEUE_CAPACITY = 100;

    public static void main(String[] args) {

        ExecutorService executorService = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
                0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(QUEUE_CAPACITY));

        List<String> taskList = new LinkedList<>();

        taskList.add("task-1");
        taskList.add("task-2");
        taskList.add("task-3");
        taskList.add("task-4");
        taskList.add("task-5");
        taskList.add("task-6");

        final CountDownLatch countDownLatch = new CountDownLatch(taskList.size());

        taskList.forEach(taskName -> {

            System.out.println(taskName);

            Task task = new Task(taskName, countDownLatch);

            executorService.submit(task);

        });

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        executorService.shutdown();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (executorService.isTerminated()) {
            System.out.println("thread pool is terminated!");
        }


    }
}
